<template>
  <!-- PersonCard 名片 -->
  <PageContainer v-model:enter-options="enterOptions">
    <view class="card-container">
      <Header v-model="headerHeight" title="个人名片" />
      <Box :contentPTop="30" :warpMBottom="0">
        <CardInfo :detail="cardDetail" @refresh="__init" />
      </Box>
      <Box v-if="cardDetail?.orgTenantName" :warp-m-bottom="0">
        <SourceView :org-tenant-name="cardDetail?.orgTenantName" :info="sourceInfo" />
      </Box>
      <Box :warpMBottom="0">
        <BrowseInfo
          :info="cardDetail?.browseInfo"
          :card-type="ApplyTypeEnum.PERSON"
          :card-id="cardDetail?.id"
          :id="id"
        >
          <view
            v-if="cardDetail?.unlockLeading && cardDetail?.phone"
            class="save-contacts"
            @click="addPhoneContact"
          >
            <view class="ali-icon">&#xe640;</view>
            <text>存入手机通讯录</text>
          </view>
        </BrowseInfo>
      </Box>
      <CardBtns :detail="cardDetail" @refresh="__init" />
      <view v-if="getShowCoupon" class="card-AD" @click="cardADClick">
        <image
          v-if="cocInfo.id === cardDetail?.leaderId"
          class="card-AD__img"
          src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/card-AD.png"
        />
        <image
          v-else
          class="card-AD__img"
          src="https://hb-saas.obs.cn-south-1.myhuaweicloud.com/mall/saas/card-AD-2.png"
        />
      </view>
      <Box v-if="cardDetail?.personalHonorList?.length" title="社会荣誉" :warpMBottom="0">
        <Honor :icon-type="1" :list="cardDetail.personalHonorList" />
      </Box>
      <Box v-if="cardDetail?.socialIdentityList?.length" title="社会职务" :warpMBottom="0">
        <Honor :icon-type="3" :list="cardDetail.socialIdentityList" />
      </Box>
      <Box
        title="个人简介"
        v-if="imgList.length || videoInfo.videoUrl || cardDetail?.briefIntroduction"
        :warp-m-bottom="0"
      >
        <ElegantDemeanour
          v-if="imgList.length"
          v-model="imgList"
          :cardType="ApplyTypeEnum.PERSON"
        />
        <template v-if="videoInfo.videoUrl">
          <CuttingLine background-color="transparent" :margin-bottom="0" />
          <VideoPlay v-model="videoInfo" />
        </template>
        <template v-if="cardDetail?.briefIntroduction">
          <CuttingLine background-color="transparent" :margin-bottom="0" />
          <Introduction v-model="cardDetail.briefIntroduction" />
        </template>
      </Box>
      <template v-if="cardDetail?.companiesDtoList">
        <Box title="单位简介" :content-p-top="0" :warp-m-bottom="0"></Box>
        <FirmPreview :list="cardDetail.companiesDtoList" />
      </template>
      <template v-if="cardDetail && userInfo.isOpenMall">
        <ProductsList
          :header-height="headerHeight"
          :member-leading-id="cardDetail.memberLeadingId"
        />
      </template>
      <FloatingButton
        v-if="enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
        :card-type="ApplyTypeEnum.PERSON"
        :id="cardDetail?.orgCompanyId"
        :is-control-card-in="isControlCardIn"
      />
      <template v-if="cardDetail && enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE">
        <TButtonGroup
          v-if="cardDetail.isUpdate || isOneselfShare || !cardDetail.saasMerchantIsEnable"
        >
          <TButton
            v-if="cardEditButton"
            class="gutter-btn"
            :text="cardEditButton.text"
            :icon="cardEditButton.icon"
            :custom-class="cardEditButton.customClass"
            @click="cardEditButton?.clickFn"
          />
          <TButton
            class="gutter-btn"
            :text="cardShareButton.text"
            :icon="cardShareButton.icon"
            :open-type="cardShareButton?.openType"
            :custom-class="cardShareButton.customClass"
            @click="showSharePopup = true"
          />
        </TButtonGroup>
        <BottomBtnGroup
          v-else
          ref="bottomBtnGroupRef"
          :card-detail="cardDetail"
          :people-price="sourceInfo?.people"
          :contact-price="sourceInfo?.contact"
          @refresh="__init"
          @on-share="showSharePopup = true"
        >
          <SourceContent :info="sourceInfo" />
        </BottomBtnGroup>
      </template>
      <PerfectInfoDialog />
    </view>
  </PageContainer>

  <CustomShare
    v-if="cardDetail && enterOptions?.scene !== SceneValuesEnum.TIMELINE_SINGLEPAGE"
    v-model:visible="showSharePopup"
    @register="handleCustomShareRegister"
  />
</template>

<script lang="ts" setup>
  /**  PersonCard  名片 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import { computed, ref, unref } from 'vue';
  import { orgBusinessCardPersonal } from '@/api/card';
  import { type PersonalCardDetailsResult } from '@/api/card/types';
  import Header from '@/components/Header/index.vue';
  import { isLogin } from '@/utils/is';
  import Honor from '../components/honor/index.vue';
  import {
    onPageScroll,
    onShareAppMessage,
    onShareTimeline,
    onShow,
    onUnload,
  } from '@dcloudio/uni-app';
  import { useUserStoreWithOut } from '@/store/modules/user';
  import { navigateBack, navigateTo, onLoad } from '@/router';
  import { storeToRefs } from 'pinia';
  import BrowseInfo from '../components/browseInfo/index.vue';
  import Box from '../components/box/index.vue';
  import ElegantDemeanour from '../components/elegantDemeanour/index.vue';
  import { ApplyTypeEnum } from '@/enums/membershipEnum';
  import VideoPlay from '@/components/VideoPlay/index.vue';
  import Introduction from '../components/introduction/index.vue';
  import FirmPreview from '../components/firmPreview/index.vue';
  import FloatingButton from '../components/floatingButton/index.vue';
  import CuttingLine from '../components/cuttingLine/index.vue';
  import { useDebounceFn } from '@vueuse/core';
  import { createMiniCode, toSelectiveType as dynamicToSelectiveType } from '@/utils/dynamicConfig';
  import { logManager } from '@/utils/log';
  import SourceView from '../components/sourceView/index.vue';
  import CardInfo from './components/CardInfo.vue';
  import CardBtns from './components/CardBtns.vue';
  import BottomBtnGroup from './components/BottomBtnGroup.vue';
  import { UniEmitNameEnum } from '@/enums/uniEmitEnum';
  import SourceContent from '../components/sourceView/content.vue';
  import { memberCardPrice } from '@/api/member';
  import { type MemberCardPriceResult } from '@/api/member/types';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { type BtnResult } from '@/components/TButtonGroup/types';
  import PerfectInfoDialog from '@/components/PerfectInfoDialog/index.vue';
  import ProductsList from './components/ProductsList.vue';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import { SceneValuesEnum } from '@/enums/sceneValuesEnum';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { addAppShareLog } from '@/api';
  import { getPersonCardPosterData } from '../components/createPosterJson';

  const { setWxSharePath, setWxShareTimelineQuery, createShareQuery } =
    useAppShare();

  const enterOptions = ref<UniApp.GetLaunchOptionsSyncOptions>();

  const id = ref();
  const editId = ref();
  const useUser = useUserStoreWithOut();
  const { cocInfo, userInfo } = storeToRefs(useUser);
  const cardDetail = ref<PersonalCardDetailsResult>();
  const headerHeight = ref(0);

  /** 是否由名片所属人分享 */
  const isOneselfShare = ref<boolean>();

  const cardShareButton = ref<BtnResult>({
    text: '分享',
    icon: '\ue8b0',
    // openType: 'share',
    customClass: 'cardBtn',
  });
  const cardEditButton = ref<BtnResult>();

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    {
      setWxShareOptions,
      setShareLogId,
      setPosterDrawData,
      setShareTimelineContent,
      setInternalLinkOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      timeline: true,
      copyLink: true,
      insertOffiaccount: true,
    },
  });

  async function handleCustomShareRegister(e: any) {
    customShareRegister(e);
    const query = {
      id: unref(cardDetail)?.memberLeadingId || editId.value,
      isOneselfShare: unref(cardDetail)?.isUpdate || false,
    };
    const routeQuery = createShareQuery(query);
    const title = unref(cardDetail)?.isUpdate
      ? '这是我的名片，期待与您连接！'
      : `为您推荐人脉“${cardDetail.value?.name}”，快来认识！`;

    const res = await addAppShareLog({
      path: 'personCard',
      query: JSON.stringify(routeQuery),
    });

    setInternalLinkOptions({
      name: 'personCard',
      options: { id: unref(cardDetail)?.memberLeadingId || editId.value },
    });

    setShareLogId(res.id);

    const path = setWxSharePath({
      name: 'personCard',
      options: query,
    });
    const codeImg = await createMiniCode({ shareLogId: res.id });

    setWxShareOptions([
      {
        title: title,
        path,
        imageUrl: cardDetail.value?.share,
      },
    ]);

    setShareTimelineContent({
      query: setWxShareTimelineQuery(query),
      title: title,
      imageUrl: cardDetail.value?.avatar,
    });

    await setPosterDrawData(
      getPersonCardPosterData({ title: title, cardImg: cardDetail.value?.share! }, codeImg),
    );
  }

  /** 个人风采数据 */
  const imgList = ref<string[]>([]);
  /** 视频数据 */
  const videoInfo = ref({
    videoUrl: '',
    coverUrl: '',
  });

  function __init(opId?: number) {
    opId = opId || unref(memberLeadingId) || cocInfo.value.memberLeadingId;
    id.value = opId;
    editId.value = opId;
    if (opId) {
      orgBusinessCardPersonal(opId, unref(isOneselfShare)).then((r) => {
        if (r) {
          cardDetail.value = r;
          getSourceContent(r.tenantId);
          imgList.value = r.imgList || [];
          videoInfo.value.coverUrl = r.videoCover;
          videoInfo.value.videoUrl = r.video;
          if (r.isUpdate) {
            cardEditButton.value = {
              text: '编辑',
              icon: '\ue8ac',
              customClass: 'cardBlackBtn',
              clickFn: () => {
                toEdit();
              },
            };
          }
        }
      });
    } else {
      uni.showModal({
        title: '提示',
        content: '申请成为会员, 即可使用名片',
        confirmText: '立即申请',
        success: ({ confirm }) => {
          if (confirm) {
            dynamicToSelectiveType({
              linkUrl: 'selectiveType',
              isRedirectTo: true,
            });
          } else {
            navigateBack();
          }
        },
      });
    }
  }

  const sourceInfo = ref<MemberCardPriceResult>();
  function getSourceContent(tenantId: number) {
    memberCardPrice(tenantId).then((r) => {
      sourceInfo.value = r;
    });
  }

  const bottomBtnGroupRef = ref(null);
  const memberLeadingId = ref<number>();
  const isControlCardIn = ref<boolean>();
  onLoad<'PersonCard'>((op) => {
    isControlCardIn.value = op.isControlCardIn;
    let opId = op.scene || op.id;
    opId = Number(opId);
    isOneselfShare.value = op.isOneselfShare;
    memberLeadingId.value = opId;
    opId ? __init(opId) : isLogin(() => __init(opId as number), true);
    uni.$on(UniEmitNameEnum.REFRESHPREVIOUSPAGE, () => {
      (bottomBtnGroupRef.value as any)?.close?.();
      __init(opId);
    });
  }, () => {
    return { id: id.value, isOneselfShare: cardDetail.value?.isUpdate ?? false }
  });

  const getShowCoupon = computed(() => {
    const d = unref(cardDetail);
    if (!d) return false;
    if (d.isUpdate || (d.isMemberCoupon && (d.unlockContact || d.unlockLeading))) return true;
  });

  const isClickAddPhoneContact = ref(false);
  /** 保存通讯录 */
  const addPhoneContact = useDebounceFn(() => {
    if (cardDetail.value) {
      const { name, phone, avatar } = cardDetail.value;
      uni.getImageInfo({
        src: avatar,
        success: ({ path }) => {
          uni.addPhoneContact({
            firstName: name,
            photoFilePath: path,
            mobilePhoneNumber: phone,
            fail: (err) => {
              if (err.errno === 103 || err.errMsg === 'addPhoneContact:fail auth deny') {
                showFailToast();
              }
              logManager.error(err);
            },
          });
        },
      });
    }
  }, 500);

  function showFailToast() {
    uni.getSetting({
      success: ({ authSetting }) => {
        if (!authSetting['scope.addPhoneContact']) {
          uni.showModal({
            title: '提示',
            content: '使用"存入手机通讯录"功能, 需要获取"添加到通讯录"权限',
            confirmText: '获取权限',
            success: ({ confirm }) => {
              if (confirm) {
                uni.openSetting();
                isClickAddPhoneContact.value = true;
              }
            },
          });
        }
      },
    });
  }

  onShow(() => {
    isClickAddPhoneContact.value && showFailToast();
    isClickAddPhoneContact.value = false;
  });

  /** 跳转福利券列表 */
  function cardADClick() {
    isLogin(() => {
      cardDetail.value &&
        navigateTo({
          name: 'cardMemberCouponList',
          options: {
            leaderId: cardDetail.value?.leaderId,
          },
        });
    });
  }

  function toEdit() {
    isClickAddPhoneContact.value = false;
    cardDetail.value &&
      navigateTo({
        name: 'editPersonCard',
        options: {
          data: cardDetail.value,
          callback: () => {
            useUser.setUserInfo();
            __init();
          },
        },
      });
  }

  onUnload(() => {
    uni.$off(UniEmitNameEnum.REFRESHPREVIOUSPAGE);
  });

  onShareAppMessage(() => ({}));

  onShareTimeline(() => ({}));

  onPageScroll(() => {});
</script>

<style lang="scss" scoped>
  .card-container {
    .save-contacts {
      color: #2878ff;
      font-size: 23rpx;
      display: flex;
      align-items: center;
      height: inherit;
      .ali-icon {
        color: #2878ff;
        font-size: 23rpx;
        margin-right: 6rpx;
      }
    }

    .card-AD {
      padding: 30rpx;
      .card-AD__img {
        width: 100%;
        height: 122rpx;
      }
    }
  }
</style>
